<template>
  <div
    :class="animate"
    :style="{ height: height, width: width }"
    :id="chartOption.bindingDiv"
    ref="chartDiv"
  />
</template>

<script>
import echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme
import resize from "@/views/dashboard/mixins/resize";

import "../../animate/animate.css";

import { parseQueryString, fIsUrL } from "../../util/urlUtil";
import { getFormsource } from "@/api/tool/datav/formsource";
import { chartApiBar,chartBIanalysis } from "@/api/tool/datav/chartApi";

import { addOption } from "../../codegen/codegen";
import { websocketCommand } from "../../util/websocket.js";

const animationDuration = 6000;

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart"
    },
    width: {
      type: String,
      default: "100%"
    },
    height: {
      type: String,
      default: "100%"
    },
    chartOption: {
      type: Object
    }
  },
  data() {
    return {
      chart: null,
      //dataOption: this.chartOption,
      timer: "",
      wsObj: null,
      wsFlag: false,
      wsTimer: "",
      wsValue: null,
      animate: this.className
    };
  },
  watch: {
    width() {
      this.$nextTick(() => {
        this.chart.resize();
        this.setOptions(JSON.parse(JSON.stringify(this.chartOption)));
      });
    },
    height() {
      this.$nextTick(() => {
        this.chart.resize();
        this.setOptions(JSON.parse(JSON.stringify(this.chartOption)));
      });
    },
    chartOption: {
      deep: true,
      handler(newVal) {
        this.$nextTick(() => {
          this.setOptions(JSON.parse(JSON.stringify(newVal)));
        });
      }
    },
    "chartOption.theme": {
      handler() {
        this.chart.dispose();
        this.chart = null;
        this.initChart();
      }
    },
    "chartOption.timeout": {
      handler() {
        this.chart.dispose();
        this.chart = null;
        this.initChart();
      }
    },
    "chartOption.dataSourceType": {
      handler(value) {
        //切换数据源重新连接
        if (value !== "websocket") {
          this.wsFlag = false;
          //每次切换数据源恢复原来动画
          this.animate = this.className;
        }
        if (value !== "url") {
          clearTimeout(this.timer);
        } 
      }
    },
    "chartOption.interfaceKey": {
      handler(newValue, oldValue) {
        //初始化不创建连接，改变接口地址重新创建
        if (oldValue !== undefined && oldValue != "") {
          this.wsValue = null;
          this.closeWs();
          this.createWs();
          this.animate = this.className;
        }
      }
    },
    wsFlag: {
      handler(value) {
        if (!value) {
          this.wsValue = null;
          this.closeWs();
        }
      }
    },
    className: {
      handler(value) {
        this.animate = value;
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
    clearTimeout(this.timer);
    if (this.wsFlag) {
      this.closeWs();
    }
  },
  methods: {
    initChart() {
      echarts.registerTheme("customTheme", this.chartOption.theme);
      this.chart = echarts.init(this.$el, "customTheme");
      
      //判断是否开启定时器，当是访问url接口时候并且timeout不为0时候开启定时器
      if (this.timer != "") {
        clearTimeout(this.timer);
      }
      if (
        (this.chartOption.dataSourceType == 'url' || this.chartOption.dataSourceType == 'database') &&
        this.chartOption.timeout > 0
      ) {
        let timerTask = () => {
          this.setOptions(JSON.parse(JSON.stringify(this.chartOption)));
          this.timer = setTimeout(() => {
            timerTask();
          }, this.chartOption.timeout);
        };

        timerTask();
      }else{
        this.setOptions(JSON.parse(JSON.stringify(this.chartOption)));
      }
    },
    setOptions: async function(dataOption) {
      //console.log("=>", dataOption);

      //初始化数据，判断数据源
      //如果不是静态数据就调用接口给staticDataValue赋值
      if (dataOption.dataSourceType == "url") {
        let paramJson = parseQueryString(dataOption.requestParameters);
        //let interfaceURL = 'http://localhost:8088/chart/api/bar';
        let interfaceURL = dataOption.interfaceURL;
        dataOption.staticDataValue = await chartApiBar(
          dataOption.requestMethod,
          interfaceURL,
          paramJson,
          dataOption.token
        );
        //先判断输入的url是否合法
        // if(fIsUrL(dataOption.interfaceURL)) {
        //   try {
        //     //ajax请求
        //     var paramJson = parseQueryString(dataOption.requestParameters);
        //   } catch (error) {

        //   }
        // }

        //console.log(paramJson);
      } else if (dataOption.dataSourceType == "database") {
         if (dataOption.database.executeSql != undefined && dataOption.database.executeSql != '') {
          
          let result = [];
          if(dataOption.database.sqlType == 'custom'){
          
            result = await chartBIanalysis(dataOption.database);
          }
          if (result.code == 200) {
            dataOption.staticDataValue = result.data;
            //console.log(dataOption.staticDataValue);
          } else {
            alert("操作数据库错误");
          }
        }
      } else if (dataOption.dataSourceType == "form") {
        if (dataOption.formSource != undefined) {
          
          let response = await getFormsource(dataOption.formSource.id);
          dataOption.staticDataValue = JSON.parse(response.data.formData);
        }
      } else if (dataOption.dataSourceType == "websocket") {
        if (
          dataOption.interfaceKey != undefined &&
          dataOption.interfaceKey != ""
        ) {
          if (!this.wsFlag) {
            this.wsFlag = true;
            this.wsValue = null;
            this.createWs();
          }
          if (this.wsValue != null) {
            dataOption.staticDataValue = this.wsValue;
          }
        }
      }

      if (dataOption.animate != null) {
        //添加动画样式
        //animateUtil.addAnimate(dataOption.bindingDiv, dataOption.animate);
      }

      var box = document.getElementById("keyCanvas");
      if (box != null) {
        box.remove();
      }
      //创建一个画布
      let can = document.createElement("canvas");
      //设置画布的长宽
      var width = this.width.replace("px", "");
      var height = this.height.replace("px", "");

      can.id = "keyCanvas";
      can.width = width;
      can.height = height;

      let ctx = can.getContext("2d");
      var grd = ctx.createLinearGradient(0, 0, width, 0);
      if (dataOption.isTopic == true) {
        //应用主题
        if (this.chartOption.theme != null) {
          //color = dataOption.thiscolor;
          var col = dataOption.theme.color;
          dataOption.color = [[0.2, col[0]], [0.8, col[1]], [1, col[2]]];
        }
      }

      for (var i = 0; i < dataOption.color.length; i++) {
        //console.log("嘿", dataOption.color);
        grd.addColorStop(dataOption.color[i][0], dataOption.color[i][1]);
      }
      ctx.fillStyle = grd;
      ctx.fillRect(0, 0, width, height);

      //*****************************************************
      let value = dataOption.staticDataValue[0].value;
      let pointAngle =
        dataOption.startAngle -
        (value / dataOption.max) *
          (dataOption.startAngle - dataOption.endAngle);
      let thisNumber = (value / dataOption.max) * dataOption.splitNumber;
      let option = {
        bindingType: "keygauge",
        title: dataOption.title,
        color: dataOption.color,
        series: [
          {
            name: "系列名称",
            type: "gauge",
            radius: dataOption.radius,
            center: dataOption.center,
            min: dataOption.min,
            max: value,
            startAngle: dataOption.startAngle,
            endAngle: pointAngle,
            splitNumber: thisNumber,
            axisLine: { show: false },
            axisTick: { show: false },
            splitLine: {
              //刻度
              show: true,
              length: dataOption.length,
              lineStyle: {
                color: {
                  image: can, //document.getElementById('keyCanvas'),
                  //color: '#893448',
                  repeat: "no-repeat"
                },
                width: dataOption.width,
                type: "solid"
              }
            },
            data: [
              {
                value: value,
                name: dataOption.staticDataValue[0].name
              }
            ],
            detail: {
              show: dataOption.isdetail,
              formatter: "{value}",
              show: dataOption.isdetail,
              offsetCenter: dataOption.detailOffset,
              color: dataOption.detailColor,
              fontFamily: dataOption.detailFamily,
              fontSize: dataOption.detailSize,
              fontWeight: dataOption.detailWeight
            },
            pointer: { show: false },
            title: { show: false },
            axisLabel: { show: false }
          },
          {
            name: "系列名称",
            type: "gauge",
            radius: dataOption.radius,
            center: dataOption.center,
            min: value,
            max: dataOption.max,
            startAngle: pointAngle,
            endAngle: dataOption.endAngle,
            splitNumber: dataOption.splitNumber - thisNumber,
            axisLine: { show: false },
            axisTick: { show: false },
            splitLine: {
              //刻度
              show: true,
              length: dataOption.length,
              lineStyle: {
                color: dataOption.noColor,
                width: dataOption.width,
                type: "solid"
              }
            },
            detail: { show: false },
            pointer: { show: false },
            title: { show: false },
            axisLabel: { show: false }
          }
        ]
      };
      if (dataOption.isinline == "true") {
        var inline = {
          name: "系列名称",
          type: "gauge",
          radius: dataOption.inlineRadius,
          center: dataOption.center,
          startAngle: dataOption.startAngle,
          endAngle: dataOption.endAngle,
          splitLine: { show: false },
          axisTick: { show: false },
          axisLine: {
            show: true,
            lineStyle: {
              color: [["1", dataOption.inlineColor]], //dataOption.inlineColor,
              width: dataOption.inlineWidth //dataOption.inlineWidth,
            }
          },
          detail: { show: false },
          pointer: { show: false },
          title: { show: false },
          axisLabel: { show: false }
        };
        option.series.push(inline);
      }
      //执行通用处理函数
      if(dataOption.customData != undefined && dataOption.customData != ""){
        try {
          option = (
          
            //里面为要处理的代码块
          eval(dataOption.customData) 
          
          )(
            option,
            dataOption.staticDataValue,
            this.$refs.chartDiv
          );
        } catch (error) {
          console.log(error)
        }
       } 
        //交互组件配置
      if(dataOption.interactData != undefined && dataOption.interactData != ""){
          try {
              option = (        
              //里面为要处理的代码块
              eval(dataOption.interactData)             
            )(
            option,
            dataOption.staticDataValue,
            this.$refs.chartDiv
            );
          } catch (error) {
            console.log(error)
          }               
       }
      this.chart.setOption(option, true);

      addOption(dataOption.bindingDiv, option);
    },
    //  ws连接成功，后台返回的ws数据
    receiveMsg(e) {
      if (e.action == "chat") {
        // console.log('服务端推送',e);
        this.wsValue = JSON.parse(e.result);
        this.setOptions(JSON.parse(JSON.stringify(this.chartOption)));
      }
    },
    // 建立连接、发起ws请求，以心跳方式，向服务端发送数据
    createWs() {
      this.wsObj = new WebSocket(process.env.VUE_APP_WEBSOCKET);
      // 若为对象类型，以回调方式发送
      websocketCommand(
        this.wsObj,
        "create",
        5000,
        this.chartOption.interfaceKey,
        this.sendHeartBeat,
        this.receiveMsg,
        this.reconnectWs,
        this.wsWarning
      );
    },
    // 断网重连，需要处理的逻辑
    reconnectWs() {
      if (this.wsObj) {
        console.log("%c websocket_reconnect", "color:blue");
        this.createWs();
      }
    },
    // 以回调方式向服务端发送(对象类型的)心跳
    sendHeartBeat() {
      if (this.wsTimer != "") {
        clearTimeout(this.wsTimer);
      }

      let wsTimerTask = () => {
        console.log("发送心跳", "ping");
        let obj = { action: "keep", key: this.chartOption.interfaceKey };
        this.wsObj.send(JSON.stringify(obj));
        this.wsTimer = setTimeout(() => {
          wsTimerTask();
        }, parseInt(process.env.VUE_APP_WEBSOCKET_TIMEOUT));
        this.wsWarning();
      };

      wsTimerTask();
    },
    wsWarning() {
      //如果断开连接则显示组件警告动画并清除计数器
      if (this.wsObj.readyState == 3) {
        this.animate = "warning";
        clearTimeout(this.wsTimer);
      }
    },
    closeWs() {
      clearTimeout(this.wsTimer);
      websocketCommand(
        this.wsObj,
        "close",
        5000,
        this.chartOption.interfaceKey,
        this.sendHeartBeat,
        this.receiveMsg,
        this.reconnectWs,
        this.wsWarning
      );
      this.wsObj = null;
    }
  }
};
</script>
